<?php

namespace Biz\service\wiki;

use Biz\model\bigData\GoodsPortrait as mGoodsPortrait;
use Biz\model\wiki\Wiki as mWiki;
use Biz\tools\Mail;
use Doraemon\model\Elasticsearch\EsWikiListModel;


class AdmWikiPortrait
{
    const WIKI_TYPE_OPTION = [1 => '住友wiki', 2 => '品牌wiki', 3 => '门店wiki'];

    const PRICE_TAG_OPTION = [1 => '奢', 2 => '高', 3 => '中', 4 => '低'];


    public static function getScreenList($requestParams, $isExport = false)
    {
        $page = $requestParams['page'];
        $pageSize = $requestParams['per_page'];
        $condition = [];
        list($wikiCondition, $portraitCondition) = self::_screen_condition($requestParams);
        if (empty($portraitCondition)) {
            $condition = $wikiCondition;
            if (!$isExport) {
                $condition['LIMIT'] = [
                    ($page - 1) * $pageSize,
                    $pageSize
                ];
            }
            $wikiList = AdmWiki::admWikiList($condition);
            $total = $wikiList['total'];
            $list = $wikiList['list'];
        } else {
            $portraitWikiIds = mGoodsPortrait::selectByWhere($portraitCondition, 'wiki_id');
            if ($wikiCondition) {
                $wikiIds = mWiki::selectByWhere($wikiCondition, 'id');
                $ids = array_intersect($wikiIds, $portraitWikiIds);
            } else {
                $ids = $portraitWikiIds;
            }
            $total = count($ids);
            if (!$isExport) {
                $condition['id'] = array_slice($ids, ($page - 1) * $pageSize, $pageSize);
            } else {
                $condition['id'] = $ids;
            }
            $wikiList = AdmWiki::admWikiList($condition);
            $list = $wikiList['list'];
        }
        if ($list) {
            $ids = array_column($list, 'id');
            $portraitList = mGoodsPortrait::selectByWhere(['wiki_id' => $ids]);
            $portraitList = $portraitList ? array_column($portraitList, null, 'wiki_id') : [];
            $list = self::_formatPortraitList($list, $portraitList);
        }
        return [$list, $total];
    }

    /**
     * @desc 后台获取分页获取wiki信息
     * @param $adminEmail
     * @param $condition array 搜索条件
     * @return void
     */
    public static function admExportScreenList($requestParams, $adminEmail = '')
    {
        list($list, $total) = self::getScreenList($requestParams, true);

        $sheetData = [
            ['cell_title' => '商品ID', 'cell_key' => 'A', 'cell_width' => 15, 'value_key' => 'id'],
            ['cell_title' => 'WIKI ID', 'cell_key' => 'B', 'cell_width' => 15, 'value_key' => 'basic_id'],
            ['cell_title' => '商品名称', 'cell_key' => 'C', 'cell_width' => 25, 'value_key' => 'title'],
            ['cell_title' => '商品热度', 'cell_key' => 'D', 'cell_width' => 15, 'value_key' => 'hot'],
            ['cell_title' => '一级类目', 'cell_key' => 'E', 'cell_width' => 20, 'value_key' => 'first_cate'],
            ['cell_title' => '二级类目', 'cell_key' => 'F', 'cell_width' => 20, 'value_key' => 'second_cate'],
            ['cell_title' => '三级类目', 'cell_key' => 'G', 'cell_width' => 20, 'value_key' => 'third_cate'],
            ['cell_title' => '四级类目', 'cell_key' => 'H', 'cell_width' => 20, 'value_key' => 'four_cate'],
            ['cell_title' => '品牌名称', 'cell_key' => 'I', 'cell_width' => 25, 'value_key' => 'brand_name'],
            ['cell_title' => '品牌ID', 'cell_key' => 'J', 'cell_width' => 15, 'value_key' => 'brand_id'],
            ['cell_title' => '渠道', 'cell_key' => 'K', 'cell_width' => 15, 'value_key' => 'channel_type'],
            ['cell_title' => '第三方状态', 'cell_key' => 'L', 'cell_width' => 15, 'value_key' => 'channel_spu_status'],
            ['cell_title' => '审核状态', 'cell_key' => 'M', 'cell_width' => 15, 'value_key' => 'status_desc'],
            ['cell_title' => '创建时间', 'cell_key' => 'N', 'cell_width' => 20, 'value_key' => 'addtime'],
            ['cell_title' => 'wiki类型', 'cell_key' => 'O', 'cell_width' => 15, 'value_key' => 'wiki_source'],
            ['cell_title' => '价格属性', 'cell_key' => 'P', 'cell_width' => 15, 'value_key' => 'price_tag'],
            ['cell_title' => '关联note数', 'cell_key' => 'Q', 'cell_width' => 15, 'value_key' => 'note_cnt'],
            ['cell_title' => '被收藏数', 'cell_key' => 'R', 'cell_width' => 15, 'value_key' => 'fav_cnt'],
            ['cell_title' => '去购买数', 'cell_key' => 'S', 'cell_width' => 15, 'value_key' => 'buy_cnt'],
            ['cell_title' => '商品渠道曝光', 'cell_key' => 'T', 'cell_width' => 15, 'value_key' => 'goods_show_cnt'],
            ['cell_title' => '商品渠道点击数', 'cell_key' => 'U', 'cell_width' => 15, 'value_key' => 'goods_click_cnt'],
            ['cell_title' => '商品渠道ctr', 'cell_key' => 'V', 'cell_width' => 15, 'value_key' => 'goods_ctr'],
            ['cell_title' => '商品渠道去购买', 'cell_key' => 'W', 'cell_width' => 15, 'value_key' => 'goods_buy_cnt'],
            ['cell_title' => '商品渠道去购买转化', 'cell_key' => 'X', 'cell_width' => 15, 'value_key' => 'goods_buy_cvr'],
            ['cell_title' => '榜单渠道去购买', 'cell_key' => 'Y', 'cell_width' => 15, 'value_key' => 'rank_buy_cnt'],
            ['cell_title' => '内容渠道点击数', 'cell_key' => 'Z', 'cell_width' => 15, 'value_key' => 'content_click_cnt'],
            ['cell_title' => '内容渠道crv', 'cell_key' => 'AA', 'cell_width' => 15, 'value_key' => 'content_cvr'],
            ['cell_title' => '内容渠道去购买', 'cell_key' => 'AB', 'cell_width' => 15, 'value_key' => 'content_buy_cnt'],
            ['cell_title' => '内容渠道去购买转化', 'cell_key' => 'AC', 'cell_width' => 15, 'value_key' => 'content_buy_cvr'],
        ];


        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //设置表头
        foreach ($sheetData as $row) {
            $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
            $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
        }
        //设置表格数据
        $rowNum = 2; // 从第二行开始
        foreach ($list as $info) {
            foreach ($sheetData as $row) {
                $key = $row['value_key'];
                $value = isset($info[$key]) ? $info[$key] : '';
                switch ($key) {
                    case 'brand_name':
                        $value = $info['brand_info'] ? $info['brand_info']['name'] : '';
                        break;
                    case'brand_id':
                        $value = $info['brand_info'] ? $info['brand_info']['id'] : '';
                        break;
                    case 'channel_type':
                        $value = mWiki::CHANNEL_TYPE_MAP[$info['channel_type']];
                        break;
                    case 'channel_spu_status':
                        $value = mWiki::CHANNEL_STATUS_ARR[$info['channel_spu_status']];
                        break;
                    case 'wiki_source':
                        if ($info['brand_id'] > 0) {
                            $value = '品牌';
                        } else if ($info['store_id'] > 0) {
                            $value = '门店';
                        } else {
                            $value = '用户';
                        }
                        break;
                }
                $sheet->setCellValue($row['cell_key'] . $rowNum, $value);
            }
            $rowNum++;
        }
        $fileName = 'wiki商品信息' . date('YmdHis') . '.xlsx';
        if ($adminEmail) {
            $filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($filePath);
            Mail::send($adminEmail, 'wiki筛选结果', '下载日期:' . date("Y年m月d日 H:i:s"), $filePath);
        } else {
            ob_end_clean();
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
            exit();
        }
    }

    private static function _screen_condition($request)
    {
        $wikiCondition = [];//wiki商品搜索条件
        $portraitCondition = [];//wiki商品画像搜索条件

        if (isset($request['title']) && strlen(trim($request['title'])) > 0) {
            $wikiCondition['title[~]'] = trim($request['title']);
        }
        if (isset($request['wiki_id']) && ($request['wiki_id'] > 0)) {
            $wikiCondition['id'] = $request['wiki_id'];
        }
        if (isset($request['wiki_basic_style']) && ($request['wiki_basic_style'])) {
            
            $basicIds = EsWikiListModel::queryByBasicStyle($request['wiki_basic_style']);
            if($basicIds){
                $wikiCondition['basic_id'] = $basicIds;
            }
            
        }
        if (isset($request['basic_id']) && ($request['basic_id'] > 0)) {
            $wikiCondition['basic_id'] = $request['basic_id'];
        }
        if (isset($request['channel_spu_id']) && ($request['channel_spu_id'] > 0)) {
            $wikiCondition['channel_spu_id'] = $request['channel_spu_id'];
        }
        if (isset($request['channel_type']) && $request['channel_type']) {
            $wikiCondition['channel_type'] = $request['channel_type'];
        }
        if (isset($request['channel_spu_status']) && strlen($request['channel_spu_status']) > 0) {
            $wikiCondition['channel_spu_status'] = $request['channel_spu_status'];
        }
        if (isset($request['status']) && ($request['status'] !== '')) {
            $wikiCondition['status'] = $request['status'];
        }
        if (isset($request['category_id']) && $request['category_id']) {
            $wikiCondition['category_id'] = $request['category_id'];
        }
        if (isset($request['second_category_id']) && $request['second_category_id']) {
            $wikiCondition['second_category_id'] = $request['second_category_id'];
        }
        if (isset($request['third_category_id']) && $request['third_category_id']) {
            $wikiCondition['third_category_id'] = $request['third_category_id'];
        }
        if (isset($request['four_category_id']) && $request['four_category_id']) {
            $wikiCondition['four_category_id'] = $request['four_category_id'];
        }
        if (isset($request['wiki_type']) && $request['wiki_type']) {
            //1:住友wiki 2:品牌wiki 3:门店wiki
            if (in_array(1, $request['wiki_type'])) {
                if (count($request['wiki_type']) == 1) {
                    $wikiCondition['brand_id'] = 0;
                    $wikiCondition['store_id'] = 0;
                } else if (count($request['wiki_type']) == 2) {
                    if (in_array(2, $request['wiki_type'])) {
                        $wikiCondition['store_id'] = 0;
                    } else if (in_array(3, $request['wiki_type'])) {
                        $wikiCondition['brand_id'] = 0;
                    }
                }
            } else if (in_array(2, $request['wiki_type'])) {
                $wikiCondition['brand_id[>]'] = 0;
            } else if (in_array(3, $request['wiki_type'])) {
                $wikiCondition['store_id[>]'] = 0;
            }
        }
        if (isset($request['date_time']['start']) && strlen($request['date_time']['start'])) {
            $wikiCondition['addtime[>=]'] = $request['date_time']['start'];
        }
        if (isset($request['date_time']['end']) && strlen($request['date_time']['end'])) {
            $wikiCondition['addtime[<=]'] = date('Y-m-d H:i:s', strtotime($request['date_time']['end']) + 86399);
        }

        if (isset($request['price_tag']) && $request['price_tag']) {
            foreach ($request['price_tag'] as $index) {
                if (isset(self::PRICE_TAG_OPTION[$index])) {
                    $portraitCondition['price_tag'][] = self::PRICE_TAG_OPTION[$index];
                }
            }
        }

        if (isset($request['note_cnt']['start']) && is_numeric($request['note_cnt']['start']) && $request['note_cnt']['start'] >= 0) {
            $portraitCondition['note_cnt[>=]'] = $request['note_cnt']['start'];
        }
        if (isset($request['note_cnt']['end']) && is_numeric($request['note_cnt']['end']) && $request['note_cnt']['end'] >= 0) {
            $portraitCondition['note_cnt[<=]'] = $request['note_cnt']['end'];
        }

        if (isset($request['fav_cnt']['start']) && is_numeric($request['fav_cnt']['start']) && $request['fav_cnt']['start'] >= 0) {
            $portraitCondition['fav_cnt[>=]'] = $request['fav_cnt']['start'];
        }
        if (isset($request['fav_cnt']['end']) && is_numeric($request['fav_cnt']['end']) && $request['fav_cnt']['end'] >= 0) {
            $portraitCondition['fav_cnt[<=]'] = $request['fav_cnt']['end'];
        }

        if (isset($request['buy_cnt']['start']) && is_numeric($request['buy_cnt']['start']) && $request['buy_cnt']['start'] >= 0) {
            $portraitCondition['buy_cnt[>=]'] = $request['buy_cnt']['start'];
        }
        if (isset($request['buy_cnt']['end']) && is_numeric($request['buy_cnt']['end']) && $request['buy_cnt']['end'] >= 0) {
            $portraitCondition['buy_cnt[<=]'] = $request['buy_cnt']['end'];
        }

        if (isset($request['goods_click_cnt']['start']) && is_numeric($request['goods_click_cnt']['start']) && $request['goods_click_cnt']['start'] >= 0) {
            $portraitCondition['goods_click_cnt[>=]'] = $request['goods_click_cnt']['start'];
        }
        if (isset($request['goods_click_cnt']['end']) && is_numeric($request['goods_click_cnt']['end']) && $request['goods_click_cnt']['end'] >= 0) {
            $portraitCondition['goods_click_cnt[<=]'] = $request['goods_click_cnt']['end'];
        }

        if (isset($request['goods_ctr']['start']) && is_numeric($request['goods_ctr']['start']) && $request['goods_ctr']['start'] >= 0) {
            $portraitCondition['goods_ctr[>=]'] = $request['goods_ctr']['start'];
        }
        if (isset($request['goods_ctr']['end']) && is_numeric($request['goods_ctr']['end']) && $request['goods_ctr']['end'] >= 0) {
            $portraitCondition['goods_ctr[<=]'] = $request['goods_ctr']['end'];
        }

        if (isset($request['content_click_cnt']['start']) && is_numeric($request['content_click_cnt']['start']) && $request['content_click_cnt']['start'] >= 0) {
            $portraitCondition['content_click_cnt[>=]'] = $request['content_click_cnt']['start'];
        }
        if (isset($request['content_click_cnt']['end']) && is_numeric($request['content_click_cnt']['end']) && $request['content_click_cnt']['end'] >= 0) {
            $portraitCondition['content_click_cnt[<=]'] = $request['content_click_cnt']['end'];
        }

        if (isset($request['content_cvr']['start']) && is_numeric($request['content_cvr']['start']) && $request['content_cvr']['start'] >= 0) {
            $portraitCondition['content_cvr[>=]'] = (float)$request['content_cvr']['start'];
        }
        if (isset($request['content_cvr']['end']) && is_numeric($request['content_cvr']['end']) && $request['content_cvr']['end'] >= 0) {
            $portraitCondition['content_cvr[<=]'] = (float)$request['content_cvr']['end'];
        }

        return [$wikiCondition, $portraitCondition];
    }

    private static function _formatPortraitList($list, $portraitList)
    {
        foreach ($list as &$row) {
            $portraitInfo = isset($portraitList[$row['id']]) ? $portraitList[$row['id']] : [];
            $row['note_cnt'] = $portraitInfo ? $portraitInfo['note_cnt'] : '';
            $row['fav_cnt'] = $portraitInfo ? $portraitInfo['fav_cnt'] : '';
            $row['buy_cnt'] = $portraitInfo ? $portraitInfo['buy_cnt'] : '';
            $row['fav_cnt'] = $portraitInfo ? $portraitInfo['fav_cnt'] : '';
            $row['goods_show_cnt'] = $portraitInfo ? $portraitInfo['goods_show_cnt'] : '';
            $row['goods_click_cnt'] = $portraitInfo ? $portraitInfo['goods_click_cnt'] : '';
            $row['goods_ctr'] = $portraitInfo ? $portraitInfo['goods_ctr'] : '';
            $row['goods_buy_cnt'] = $portraitInfo ? $portraitInfo['goods_buy_cnt'] : '';
            $row['goods_buy_cvr'] = $portraitInfo ? $portraitInfo['goods_buy_cvr'] : '';
            $row['rank_buy_cnt'] = $portraitInfo ? $portraitInfo['rank_buy_cnt'] : '';
            $row['content_click_cnt'] = $portraitInfo ? $portraitInfo['content_click_cnt'] : '';
            $row['content_cvr'] = $portraitInfo ? $portraitInfo['content_cvr'] : '';
            $row['content_buy_cnt'] = $portraitInfo ? $portraitInfo['content_buy_cnt'] : '';
            $row['content_buy_cvr'] = $portraitInfo ? $portraitInfo['content_buy_cvr'] : '';
            $row['price_tag'] = $portraitInfo ? $portraitInfo['price_tag'] : '';
        }
        return $list;
    }
}
